<?php

/**
 * I18Nify
 * 
 * Adds the I18N helper function "__" to text between
 * html tags for templates and partials.
 * 
 * place in the root dir of your symfony project.
 * 
 * @author     Adel Abu-Saif <adeljas@msn.com>
 * @version    0.8
 * @date       22/8/2011
 */
$exclude = array('.', '..', '.svn');
$start_dir = dirname(__FILE__) . '\\apps\\frontend\\';
$processed = 0;
$create_backups = true;

function process($filename) {

    global $create_backups;

    $string = file_get_contents($filename);
    $original = $string;

    $matches = array();
    preg_match_all('/>[a-zA-Z0-9 :.?!]+</', $string, $matches);

    foreach ($matches[0] as $one) {
        $new_one = substr($one, 1, strlen($one) - 2);
        if (trim($new_one) == '')
            continue;
        $replace = "><?php echo __('$new_one') ?><";
        $string = str_replace($one, $replace, $string);
    }

    if ($original != $string) {
        if ($create_backups)
            file_put_contents("$filename.bak", $original);
        file_put_contents($filename, $string);
        return true;
    }
    return false;
}

function iterate($dir) {

    global $exclude, $start_dir, $processed;

    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
                if (in_array($file, $exclude))
                    continue;
                $current = $dir . $file;
                $type = filetype($current);
                if ($type == 'file' && (strpos($file, 'Success.php') || strpos($file, '_') === 0 || $file == 'layout.php') && strpos($file, 'bak') === false) { // @todo
                    echo ' > ';
                    echo str_replace($start_dir, '', $current);
                    if (process($current)) {
                        echo ' [modified]';
                        $processed++;
                    }
                    echo "\n";
                }

                if ($type == 'dir')
                    iterate($current . '\\');
            }
            closedir($dh);
        }
    }
}

echo "Processing :\n\n";
iterate($start_dir);
echo "\nProcessed $processed files.\n";



